<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button
          size="mini"
          type="primary"
          @click="dialogVisible = true"
        >添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list" border>
        <!-- 放置列 -->
        <el-table-column align="center" width="50" label="序号" type="index" />
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
              size="mini"
            />
            <span v-else>{{
              row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              type="textarea"
              size="mini"
              :rows="2"
              style="width: 85%"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button
                size="mini"
                type="primary"
                @click="updateConfirm(row)"
              >确认</el-button>
              <el-button
                size="mini"
                @click="row.isEdit = false"
              >取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button
                type="text"
                size="mini"
                @click="editRow(row)"
              >编辑</el-button>
              <template>
                <el-popconfirm title="确定删除当前角色吗？" @onConfirm="delConfirm(row.id)">
                  <el-button
                    slot="reference"
                    type="text"
                    size="mini"
                    style="margin-left: 10px"
                  >删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </template></el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row
        type="flex"
        style="height: 60px; margin-top: 30px"
        align="middle"
        justify="center"
      >
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :current-page="params.page"
          :page-size="params.pagesize"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <el-dialog title="新增角色" :visible.sync="dialogVisible" width="500px">
      <el-form
        ref="formDom"
        label-width="80px"
        :model="addForm"
        :rules="formRules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name" size="mini" style="width: 85%" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="addForm.state"
            :active-value="1"
            :inactive-value="0"
            size="mini"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            size="mini"
            :rows="3"
            style="width: 85%"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button
                type="primary"
                size="mini"
                @click="confirm"
              >确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
      <el-tree
        ref="permTree"
        :data="permissionData"
        :props="{label:'name'}"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        node-key="id"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { addRole, getRoleList, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { transList2TreeData } from '@/utils'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      currentRoleId: null,
      permIds: [], // 选中的数据
      showPermissionDialog: false,
      permissionData: [], // 树形列表
      list: [],
      total: 0,
      params: {
        page: 1,
        pagesize: 5
      },
      dialogVisible: false,
      addForm: {
        name: '',
        state: 1, //  默认为1启用 关闭 0 打开1
        description: ''
      },
      formRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 分配权限确定
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    },
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id) // 回显的数据
      this.permIds = permIds
      this.permissionData = transList2TreeData(await getPermissionList(), 0) // 树形列表数据
      this.showPermissionDialog = true
    },
    async getList() {
      const { rows, total } = await getRoleList(this.params)
      this.list = rows
      this.total = total
      // 动态添加 编辑标记 isEdit
      this.list.forEach((item) => {
        this.$set(item, 'isEdit', false)
        // 缓存编辑的数据
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    editRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    handleCurrentChange(value) {
      this.params.page = value
      this.getList()
    },
    async confirm() {
      await this.$refs.formDom.validate()
      await addRole(this.addForm)
      this.$message.success('新增角色成功')
      this.getList()
      this.btnCancel()
    },
    btnCancel() {
      this.$refs.formDom.resetFields() // 重置表单数据
      this.dialogVisible = false // 关闭弹层
    },
    async updateConfirm(row) {
      if (!row.editRow.name || !row.editRow.description) {
        this.$message.error('角色名称和描述不能为空')
        return false
      }
      await updateRole({ id: row.id, ...row.editRow })
      this.$message.success('角色更新成功')
      Object.assign(row, {
        isEdit: false,
        ...row.editRow
      })
    },
    async delConfirm(id) {
      await delRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) this.params.page--
      this.getList()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.role-operate {
  margin-bottom: 10px;
}
</style>
